/* eslint-disable */
/**
 * 地图气泡公用组件
 */
import sgisMapBase from '../../sfgis.map.base';
import mapTool from "@/utils/map/sfgis.map.tool.js";
import $ from 'jquery';
import microConfig from 'static/config/micro.js';
import * as microAPI from "@/pages/micro/api/micro.js";
let circleLayer = null; // 周边查询图层

// 暴露全局的popup变量
let popup = new mapboxgl.Popup({
    className: 'marker-popup-searchInfo',
    anchor: 'left',
    closeButton: true,
    closeOnClick: false,
    maxWidth:'350px',
    offset: {
        'left': [12, -5],
    }
  });

let popupDefaultShowInfo = microConfig.popupDefaultShowInfo;
let showMorePanelFunc ;
let showMOrePanelBuildFunc;
let HYDMiden={};//行业代码
let selectHYDMCode = {};
// export default {
// 地图事件(麻点图、marker图)
let openPopup = function (popupData,showMorePanel) {
    clearPopup();
    if(showMorePanel){
        showMorePanelFunc = showMorePanel;
    }
    let map = sgisMapBase.getMap()
    getTableIden();
    let HTMLElement = getInfo(popupData.data)
   
    let lngLat = [popupData.lon,popupData.lat];
    // 此处查询麻点相信信息并展示
    if (popupData && popupData.data) {
        setTimeout(() => {
            let div = document.createElement('div');
            div.className="marker-popup-"+ map._container.id;
            div.innerHTML="<div>"+
            HTMLElement
            +"</div>";
            popup.setLngLat(lngLat)
                .setDOMContent(div) // sets a popup on this marker
                .addTo(map);

            $('#peripheralquery').click(() => {
                peripheralquery(popupData.data)
            })
            // $('#lookScene').click(() => {
            //     lookScene()
            // })
            $('#showMore').click(() => {
                showMore(showMorePanelFunc,popupData)
            })
            $('#hiddenMore').click(() => {
                hiddenMore()
            })
            $('#searchPOI').click(() => {
                searchPOI(popupData)
            })
            $("#searchPOI_input").on('input propertychange',function(event){
                let word = $("#searchPOI_input").val();
                getIdenByWords(word)
            })
            $("#searchPOI_input").on('focus',function(event){
                $("#peripQueryView .idenlist").removeClass("hidden");
            })
            //输入框的enter事件
            $('#searchPOI_input').bind('keydown', function (event) {
                if (event.keyCode == "13") {
                    searchPOI(popupData)
                }
            });

            EventBus.$emit('highLightResLi', popupData.id)

            $("#peripQueryViewcheckbox button").click((e)=>{
                selectHYDL(e);
            })
        }, 0)
    }
    // EventBus.$emit('highLightResLi', data.data.ID.value)
};

let findPockingLayer = function () {
    let layers = sgisMapBase.getMap()._layers
    for (let key in layers) {
        if (layers[key].layerId && layers[key].layerId.indexOf("markerLargeLayer") > -1) {
            return layers[key]
        }
    }
    return false
};
// 列表事件
let highLightMarker = function (map, id) {
    let pockingLayer = this.findPockingLayer()
    if (!pockingLayer) {
        return
    }
    map.closePopup(map._popup)
    let datas = []
    let series = pockingLayer._echartsOptions.series[0]
    series.data.map(item => {
        if (item.data.ID.value === id) {
            datas.push(item)
        }
    })
    let latlng = L.latLng(datas[0].lat, datas[0].lon)
    map.setView(latlng, 15)

    let HTMLElement = getInfo(datas[0].data)
    setTimeout(() => {
        popup
            .setLatLng(L.latLng(datas[0].lat, datas[0].lon))
            .setContent(HTMLElement) // 查询结果弹窗
            .openOn(map)
        $('#peripheralquery').click(() => {
            peripheralquery(datas[0].data)
        })
        $('#lookScene').click(() => {
            lookScene()
        })
        $('#showMore').click(() => {
            showMore(showMorePanelFunc,datas[0])
        })
        $('#hiddenMore').click(() => {
            hiddenMore()
        })
        $('#searchPOI').click(() => {
            searchPOI(datas[0])
        })
        $("#searchPOI_input").on('input propertychange',function(event){
            let word = $("#searchPOI_input").val();
            getIdenByWords(word)
        })
        //输入框的enter事件
        $('#searchPOI_input').bind('keydown', function (event) {
            if (event.keyCode == "13") {
                searchPOI(datas[0])
            }
        });
    }, 0)
};

let openBuildPopup = function(buildData,callback){
    clearPopup();
    let map = sgisMapBase.getMap()
    let dataList=buildData.dataList;
    let latlon = buildData.latlon;
    let HTMLElement = getBuildInfo(dataList)
    // 此处查询麻点相信信息并展示
    
    setTimeout(() => {
        let div = document.createElement('div');
        div.className="marker-popup-build-"+ map._container.id;
        div.innerHTML="<div>"+
        HTMLElement
        +"</div>";
        popup.setLngLat(latlon)
            .setDOMContent(div) // sets a popup on this marker
            .addTo(map);

            callback&&callback();
    }, 0)
    

};
/**
 * 拼接建筑物列表弹窗信息
 * @param {*} data 
 */
function getBuildInfo(data){
    let HTMLElement = "<div class='popupInfo'><p class='title'>信息</p>";
    let allInfo = "<div class='allInfo' style='max-height:200px;overflow:auto;'><ul>";
    if(data.length>0){
        for (let j in data) {
            allInfo += '<li id="'+data[j].id+'">' + data[j].name + '</li>'
        }
    }else{
        allInfo += '<li >暂无数据</li>'
    }

    allInfo += "</ul></div>";
    HTMLElement += allInfo;

    HTMLElement += '</div>';

    return HTMLElement
}
/**
 * 拼接marker弹窗信息
 * @param {*} data 
 */
function getInfo(data) {

    // let showScene = findOrganizeCode(data)
    let HTMLElement = "<div class='popupInfo'><p class='title'>信息</p>";
    let allInfo = "<div class='allInfo hidden' style='max-height:200px;overflow:auto;'><ul>";
    let defaultShowInfo = "<div class='defaultShowInfo'><ul>";
    for (let j in data) {
        if(j!="info"){
            allInfo +='<li>'+data[j].name+":"+data[j].value+'</li>';
        }
        if (popupDefaultShowInfo.includes(j)) {
            defaultShowInfo += '<li>' + data[j].name + '&nbsp;:&nbsp;&nbsp;' + data[j].value + '</li>'
        }
    }

    allInfo += "</ul></div>";
    defaultShowInfo += "</ul></div>";
    HTMLElement += defaultShowInfo;
    HTMLElement += allInfo;
    HTMLElement += '<div class="popup-todo">'
    HTMLElement += '<a id="peripheralquery">周边查询</a>'
    HTMLElement += '<a id="showMore">更多</a><a id="hiddenMore" class="hidden">收起</a>'
    HTMLElement += '</div>'
    // HTMLElement += '</div>'




    HTMLElement += '<div class="peripQueryView mapqueryInfo hidden" id="peripQueryView">';
    HTMLElement += '<div class="checkboxcontent" id="peripQueryViewcheckbox">';
    HTMLElement += '<label >热门标签:</label>';
    HTMLElement += '<button value="F,G,H,I,J" id="selectAllHYDL" class="selectAllHYDL" name="批发零售,交通仓储邮政,住宿餐饮,信息软件,金融">全部 </button>';
    HTMLElement += '<button class="active" value="F" name="批发零售">批发零售</button>';
    HTMLElement += '<button value="G" name="交通仓储邮政">交通仓储邮政</button> ';   
    HTMLElement += '<button value="H" name="住宿餐饮">住宿餐饮</button>';    
    HTMLElement += '<button value="I" name="信息软件">信息软件</button>';    
    HTMLElement += '<button value="J" name="金融">金融</button>';    
    HTMLElement += '</div>';
    HTMLElement += '<div class="searchcontent">';
    HTMLElement += '<label >行业检索:</label>';
    HTMLElement += '<input type="text" id="searchPOI_input"/>';
    HTMLElement += '<select name="querymap" id="querymapradios">';
    HTMLElement += '<option value="100">100米</option>';
    HTMLElement += '<option value="300">300米</option>';
    HTMLElement += '<option value="500">500米</option>';
    HTMLElement += '<option value="1000">1000米</option>';
    HTMLElement += '</select>';
    HTMLElement += '<button id="searchPOI">搜索</button>';
    HTMLElement += '</div>';
    HTMLElement += '<ul class="idenlist"></ul>';
    HTMLElement += '</div>';


    // HTMLElement += "<div class='mapqueryInfo hidden' >";
    // HTMLElement += "<div class='radio-group'><input type = 'radio' name ='querymap' value = '500' title='500米' checked/ ><label for='500'>500米</label>";
    // HTMLElement += "<input type = 'radio' name ='querymap' value = '1000' title='1000米'/ ><label for='1000'>1000米</label>";
    // HTMLElement += "<input type = 'radio' name ='querymap' value = '1500' title='1500米'/ ><label for='1500'>1500米</label></div>";

    // HTMLElement+='<input type="text" name="name" value=""><button id="searchPOI">搜索</button>';

    HTMLElement += '</div>';

    return HTMLElement
}


/**
 * 判断当前数据是否有三维模型
 * @param {*} data 
 */
function findOrganizeCode(data) {
    let configData = SceneConfig.datas
    if (data.hasOwnProperty("TYPE") && data.TYPE == 'ESSearch') { //从ES查询的数据指标名称不一致，特殊处理
        for (let i = 0; i < configData.length; i++) {
            let element = configData[i];
            if (element.code[0] == data.BBQ_.value &&
                element.code[1] == data.BTYPE_.value &&
                element.code[2] == data.USERID_.value) {
                return element.url
            }
        }
    } else {
        for (let i = 0; i < configData.length; i++) {
            let element = configData[i];
            if (data.BBQ &&  data.BTYPE && data.USERID && 
                element.code[0] == data.BBQ.value &&
                element.code[1] == data.BTYPE.value &&
                element.code[2] == data.USERID.value) {
                return element.url
            }
        }
    }
    return false
}

/**
 * 周边查询
 * @param {Object} info 对应的点击信息 
 */
function peripheralquery(info) {
    let item = $(".peripQueryView");
    if ($(item).hasClass("hidden")) {
        item.removeClass("hidden");
    } else {
        item.addClass("hidden");
    }
}

/**
 * 查看三维
 */
function lookScene() {
    let dom = $('#lookScene')
    let url = dom[0].getAttribute('data-url')
    EventBus.$emit('lookScene', url)
}

/**
 * 更多
 * @param {Object} info 对应的点击信息
 */
function showMore(func,data) {
    if(func){
        func(data);
    }else{
        $(".marker-popup-map .allInfo").removeClass("hidden");
        $(".marker-popup-map .defaultShowInfo").addClass("hidden");
        $(".marker-popup-map #hiddenMore").removeClass("hidden");
        $(".marker-popup-map #showMore").addClass("hidden");
    }
    
}
/**
 * 收起更多
 * @param {Object} info 对应的点击信息
 */
function hiddenMore(info) {
    $(".marker-popup-map .allInfo").addClass("hidden");
    $(".marker-popup-map .defaultShowInfo").removeClass("hidden");
    $(".marker-popup-map #hiddenMore").addClass("hidden");
    $(".marker-popup-map #showMore").removeClass("hidden");
}

/**
 * 查询天地图数据
 * @param {Object} info 对应的点击信息
 */
function searchPOI(info) {
    let selectedObjTable = JSON.parse(sessionStorage.getItem("selectedObjTable"));
    let HYDL = "";
    let valueName = "";
    let list = $("#peripQueryViewcheckbox button.active");
    for(let i= 0;i < list.length;i++ ){
        let HYDLVal = $(list[i]).attr("value");
        let HYDLName = $(list[i]).attr("name");
        if(HYDL.indexOf(HYDLVal)==-1){
            HYDL += (HYDL==""?HYDLVal:","+HYDLVal);
            valueName += (valueName==""?HYDLName:","+HYDLName);
        }
    }
    if(selectHYDMCode.hasOwnProperty("id")){
        if(HYDL.indexOf(selectHYDMCode.code)==-1){
            valueName += (valueName==""?selectHYDMCode.text:","+selectHYDMCode.text);
            HYDL += (HYDL==""?selectHYDMCode.code:","+selectHYDMCode.code);
        }
    }
    let HYDMZM = microConfig.HYDM;
    for(let j in HYDMZM){
        if(HYDL.indexOf(j)!=-1){
            HYDL = HYDL.replace(j,HYDMZM[j])
        }
    }
    if(HYDL==""){
        alert("请选择条件再进行查询")
        return false;
    }else{
        let peripheralqueryHYDL = microConfig.peripheralqueryHYDL;
        peripheralqueryHYDL.value = HYDL;
        peripheralqueryHYDL.valueName = "行业大类  属于  "+valueName;
        peripheralqueryHYDL.microid = selectedObjTable.id;
        peripheralqueryHYDL.field = HYDMiden.idenCode;
        peripheralqueryHYDL.fieldName = HYDMiden.idenName;
        peripheralqueryHYDL.groupId = HYDMiden.identid;

        let conditions = [];
        conditions.push(peripheralqueryHYDL);

        let map = sgisMapBase.getMap();
        let SMX= info.lon, SMY=info.lat;

        let queryRadius = $('#querymapradios').val();

        let circleparams = {
            SMX: SMX,
            SMY: SMY,
            queryRadius: queryRadius
        }

        drawBufferQuery_CIRCLEMARKER(circleparams);
        EventBus.$emit("updateMicroSearchParams", conditions);

        let zoom = map.getZoom();
        if(zoom<10){
            map.flyTo({
            center: [SMX,SMY],
            speed: 1.5,
            zoom: 13
            })
        }
    }
}

//获取“HYDM”指标
function getTableIden(){
    let that = this;
    let selectedObjTable = JSON.parse(sessionStorage.getItem("selectedObjTable"));
    let req = {
      miid: selectedObjTable.id,
      iden_type: 4
    };
    HYDMiden = {};
    microAPI
      .getSelectedTableIden(req)
      .then(res => {
        if (res.message == "success" && res.data.length > 0) {
          let arr = res.data;
          arr.map(item => {
            if (item.idenAliasCode == "HYDM") {
                HYDMiden = item;
            }
          });
        }
      })
      .catch(error => {
        console.log(error);
      });
}

//模糊搜索枚举值
function getIdenByWords(word){
    let that = this;
    let req = {
        mid :HYDMiden.identid,
        vid :HYDMiden.identVersion,
        word :word 
    }
    microAPI
      .getIdenByWords(req)
      .then(res => {
        if (res.message == "success") {
          $("#peripQueryView .idenlist").empty();
          let arr = res.data;
          console.log('arr:',arr)
          if(arr.length>0){
            let html = "";
            arr.map((item)=>{
                let list = "<li code='"+item.code+"' id='"+item.id+"'>"+item.name+"</li>";
                html +=list;
            })
            $("#peripQueryView .idenlist").html(html);
            $("#peripQueryView .idenlist").removeClass("hidden");
            $("#peripQueryView .idenlist li").click(function(e){
                selectSearchIden(e);
            })
          }else{
            let html = "<p>无行业数据</p>";
            $("#peripQueryView .idenlist").html(html);
          }
        }
      })
      .catch(error => {
        console.log(error);
      });
}

//选中指标
function selectSearchIden(e){
    let dom =$(e.target);
    let code =  dom.attr("code");
    let text = dom.text();
    let id = dom.attr("id");
    selectHYDMCode = {
        code:code,
        text:text,
        id:id
    };
    $("#searchPOI_input").val(text);
    $("#peripQueryView .idenlist").addClass("hidden");
}

/**
 * 根据坐标用缓冲查询实现查询周边
 * @param {Object} params 对应的点击信息
 */
function drawBufferQuery_CIRCLEMARKER(circleparams){
    let bufferRegionLevel = 8;
    let radioFun = "DRAW";
    let inputBuffer = circleparams.queryRadius;
    let geometry = {
        type: "Point",
        coordinates:[circleparams.SMX,circleparams.SMY]
    }
    mapTool.drawBufferQuery_zhoubian(bufferRegionLevel, "1", radioFun, inputBuffer/100000,geometry)
}



  //清除信息框
function clearPopup(){
    if(popup){
      popup.remove();
    }
}


function selectAllHYDL(e){

    $(e.target).addClass("active");
    $(e.target).siblings("button").addClass("active");
}

function selectHYDL(e){
    let ele = $(e.target);
    if(ele.hasClass("selectAllHYDL")&&ele.hasClass("active")){
        ele.removeClass("active");
        ele.siblings("button").removeClass("active");
    }else if(ele.hasClass("selectAllHYDL")&&!ele.hasClass("active")){
        ele.addClass("active");
        ele.siblings("button").addClass("active");
    }else if(!ele.hasClass("selectAllHYDL")&&ele.hasClass("active")){
        ele.removeClass("active");
        ele.siblings("button.selectAllHYDL").removeClass("active");
    }else if(!ele.hasClass("selectAllHYDL")&&!ele.hasClass("active")){
        ele.addClass("active");
    }
}
export default {
    openPopup: openPopup,
    findPockingLayer: findPockingLayer,
    highLightMarker: highLightMarker,
    clearPopup:clearPopup,
    openBuildPopup:openBuildPopup
}
